<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;

// 玩家 根据游戏角色  新增 流失用户统计 只与昨日对比
class NoticeInterval extends  Model{

	protected $table='notice_interval';
    //protected $_db_select = 'mysql';

    public $timestamps = true;

    const DB_FIELDS = 'id,title,content,start_time,end_time,add_time,send_time,game_msgid,area,limit_times,send_times,gap,trigger_time';

    
	public function paginate()
    {
    	$perPage = Request::get('per_page', 15);
        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table($this->table)->where('deleted_at', 0)->orderBy("id", 'desc')->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $data = $rw->get();
        $data = $data->toArray();

        $total = \DB::connection($this->selectdb())->table($this->table)->where('deleted_at', 0)->get()->count();

        //$data = json_decode($data, true);
        // var_dump($data);
        // exit;

        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    public function selectdb()
    {
        return 'mysql';
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['title']){
            $rw->where("title", 'like', $cond["title"].'%');
        }
        if ($cond['area']){
            $rw->where("area", $cond['area']);
        }

        if (isset($cond["send_time"])){
            $send_time = $cond['send_time'];
            (0 == $send_time) && $rw->where('send_time', 0);
        }
    }

    public static function assignByOut(&$one, $out){
        $flds = explode(',', self::DB_FIELDS);
        
        foreach ($flds as $fld) {
            isset($out[$fld]) && $one->{$fld} = $out[$fld];
        }

        \Log::debug('notice save', [$out]);
        !$out['game_msgid'] && $one->game_msgid = \App\Service\MessageDef::p2g_notice_request;
        // if (is_array($one->area_list)) {
        //     $one->area_list = implode(",", $one->area_list);
        // }
        !$out['start_time'] && $one->start_time = 0;
        !$out['end_time'] && $one->end_time = 0;
        !$out['gap'] && $one->gap = 0;
        !$out['area_list'] && $one->area_list = '';
        !$one->send_time && $one->send_time = time();

        if ( intval($one->start_time).'' !== $one->start_time . ''  ) {
            $one->start_time = strtotime($one->start_time);
        }

        if ( intval($one->end_time).'' !== $one->end_time . ''  ) {
            $one->end_time = strtotime($one->end_time);
        }
    }

}
